package com.gonsin.ta.logic.parse;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.gonsin.ta.logic.TA;
import com.gonsin.ta.logic.enums.TaResult;
import com.gonsin.ta.logic.parse.condition.context.ChainContextImpl;
import com.gonsin.ta.logic.parse.condition.Condition;
import com.gonsin.ta.logic.parse.condition.Executable;
import com.gonsin.ta.logic.parse.serialize.ChainSerial;
import com.gonsin.ta.logic.parse.serialize.ConditionSerial;
import com.gonsin.ta.logic.parse.serialize.SerializeContext;
import com.gonsin.ta.logic.parse.serialize.TaDeserializable;
import com.google.gson.annotations.Expose;
import lombok.Getter;
import lombok.Setter;

import java.util.ArrayList;
import java.util.List;

/**
 * 一个任务的节点的集合
 */
@Getter
@Setter
public class Chain implements Executable {

    /**
     * 流程id
     */
    private String chainId;

    /**
     * 流程名字
     */
    private String chainName;

    /**
     * 流程源码
     */
    private String qlScript;

    /**
     * 文件名字
     */
    @JsonIgnore
    @Expose(serialize = false, deserialize = false)
    private transient String filename;

    /**
     * 流程具体执行内容
     */
    private List<Condition> conditionList;

    @Override
    public void execute(ChainContextImpl context) throws Exception {

        for(Condition condition : conditionList){
            condition.execute(context);
        }
        if(context.getResult() == null){
            context.setResult(TaResult.FINISHED);
        }
        if(TA.LOG){
            TA.log().info("TA - 流程实例【{}】执行完毕", context.getInstanceId());
        }
    }

    @Override
    public TaDeserializable toSerializable(SerializeContext serializeContext) {
        ChainSerial chainSerial = new ChainSerial();
        List<ConditionSerial> objects = new ArrayList<>();
        for(Condition condition : conditionList){
            objects.add((ConditionSerial) condition.toSerializable(serializeContext));
        }
        chainSerial.setConditionSerials(objects);
        chainSerial.setChainName(chainName);
        chainSerial.setChainId(chainId);
        chainSerial.setQlScript(qlScript);
        return chainSerial;
    }
}
